<script setup lang="ts">
import type { CSSProperties } from 'vue'
import { nextTick, PropType, ref, unref, watch } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { vue } from '@codemirror/lang-vue'
import { oneDark } from '@codemirror/theme-one-dark'
import { string } from 'vue-types'

interface Props {
  codeStyle?: CSSProperties // 代码样式
  dark?: boolean
}
const props = defineProps({
  codeStyle: {
    type: Object,
    default: () => null
  },
  dark: {
    type: Boolean,
    default: () => false
  },
  disabled: {
    type: Boolean,
    default: () => false
  },
  code: {
    type: string,
    default: () => ''
  }
})

// interface Props {
//   codeStyle?: CSSProperties // 代码样式
//   dark?: boolean // 是否暗黑主题
//   code?: string // 代码字符串
//   // placeholder?: string // 占位文本
//   // autofocus?: boolean // 自动聚焦
//   // disabled?: boolean // 禁用输入行为和更改状态
//   // indentWithTab?: boolean // 启用tab按键
//   // tabSize?: number // tab按键缩进空格数
// }
const myCodemirror = ref()
const extensions = props.dark ? [vue(), oneDark] : [vue()]
const codeValue = ref(props.code)
const disabledFlag = ref(props.disabled)
const emits = defineEmits(['update:code', 'ready', 'change', 'focus', 'blur'])
function handleReady(payload: any) {
  // console.log('ready')
  emits('ready', payload)
}
function onChange(value: string, viewUpdate: any) {
  console.log('onchage', value)
  emits('change', value, viewUpdate)
  emits('update:code', value)
}
function onFocus(viewUpdate: any) {
  emits('focus', viewUpdate)
}
function onBlur(viewUpdate: any) {
  emits('blur', viewUpdate)
}
function getScrollInfo(element) {
  const { scrollTop, scrollLeft, scrollWidth, clientWidth, clientHeight } = element
  return {
    scrollTop, // 滚动的垂直距离
    scrollLeft, // 滚动的水平距离
    scrollWidth, // 内容的总宽度
    clientWidth, // 视口的宽度
    clientHeight
  }
}
watch(
  () => props.code,
  async (code) => {
    codeValue.value = code!
    await nextTick()
    //自动滚动到底部
    const editorElement = myCodemirror.value.$el.querySelector('.cm-editor')
    if (editorElement) {
      const scrollContainer = editorElement.querySelector('.cm-scroller')
      if (scrollContainer) {
        scrollContainer.scrollTop = scrollContainer.scrollHeight
      }
    }
  }
)
</script>
<template>
  <div>
    <Codemirror
      ref="myCodemirror"
      v-model="codeValue"
      :disabled="disabledFlag"
      :style="codeStyle"
      :extensions="extensions"
      @ready="handleReady"
      @change="onChange"
      @focus="onFocus"
      @blur="onBlur"
      v-bind="$attrs"
      :autoScroll="true"
      :lineWrapping="true"
    />
  </div>
</template>
<style lang="less" scoped>
:deep(.cm-editor) {
  height: 100%;
  color: #2aff2e;
  border-radius: 8px;
  outline: none;
  border: 1px solid transparent;
  .cm-scroller {
    border-radius: 8px;
  }
}
</style>
